#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <mosquitto.h>

// 简化的测试配置
#define TEST_BROKER_HOST "test.mosquitto.org"  // 更稳定的测试代理
#define TEST_BROKER_PORT 1883
#define TEST_CLIENT_ID   "simple_test_client"
#define TEST_TOPIC       "test/simple"

static int running = 1;

void signal_handler(int sig) {
    printf("\n收到信号 %d，正在退出...\n", sig);
    running = 0;
}

void on_connect(struct mosquitto *mosq, void *obj, int rc) {
    if (rc == 0) {
        printf("✅ 连接MQTT代理成功!\n");
        printf("📤 订阅主题: %s\n", TEST_TOPIC);
        mosquitto_subscribe(mosq, NULL, TEST_TOPIC, 0);
    } else {
        printf("❌ 连接失败，错误代码: %d\n", rc);
        switch(rc) {
            case 1: printf("   原因: 协议版本不支持\n"); break;
            case 2: printf("   原因: 客户端ID不合法\n"); break;
            case 3: printf("   原因: 代理服务器不可用\n"); break;
            case 4: printf("   原因: 用户名或密码错误\n"); break;
            case 5: printf("   原因: 未授权\n"); break;
            default: printf("   原因: 未知错误\n"); break;
        }
        running = 0;
    }
}

void on_disconnect(struct mosquitto *mosq, void *obj, int rc) {
    if (rc == 0) {
        printf("📴 主动断开连接\n");
    } else {
        printf("⚠️  意外断开连接 (代码: %d)\n", rc);
    }
}

void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) {
    printf("📨 收到消息:\n");
    printf("   主题: %s\n", msg->topic);
    printf("   内容: %.*s\n", msg->payloadlen, (char*)msg->payload);
    printf("   QoS: %d\n", msg->qos);
    printf("   保留: %s\n", msg->retain ? "是" : "否");
}

void on_publish(struct mosquitto *mosq, void *obj, int mid) {
    printf("📤 消息发送成功 (ID: %d)\n", mid);
}

void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) {
    printf("📋 订阅成功 (ID: %d, QoS: %d)\n", mid, granted_qos[0]);
}

int main(int argc, char *argv[]) {
    struct mosquitto *mosq = NULL;
    int rc;
    
    // 设置信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    printf("=== MQTT简单测试客户端 ===\n");
    printf("代理: %s:%d\n", TEST_BROKER_HOST, TEST_BROKER_PORT);
    printf("客户端ID: %s\n", TEST_CLIENT_ID);
    printf("测试主题: %s\n", TEST_TOPIC);
    printf("按 Ctrl+C 退出\n\n");
    
    // 初始化mosquitto库
    rc = mosquitto_lib_init();
    if (rc != MOSQ_ERR_SUCCESS) {
        printf("❌ 初始化mosquitto库失败: %s\n", mosquitto_strerror(rc));
        return 1;
    }
    
    // 创建mosquitto实例
    mosq = mosquitto_new(TEST_CLIENT_ID, true, NULL);
    if (!mosq) {
        printf("❌ 创建mosquitto实例失败\n");
        mosquitto_lib_cleanup();
        return 1;
    }
    
    // 设置回调函数
    mosquitto_connect_callback_set(mosq, on_connect);
    mosquitto_disconnect_callback_set(mosq, on_disconnect);
    mosquitto_message_callback_set(mosq, on_message);
    mosquitto_publish_callback_set(mosq, on_publish);
    mosquitto_subscribe_callback_set(mosq, on_subscribe);
    
    printf("🔌 正在连接到 %s:%d ...\n", TEST_BROKER_HOST, TEST_BROKER_PORT);
    
    // 连接到代理
    rc = mosquitto_connect(mosq, TEST_BROKER_HOST, TEST_BROKER_PORT, 60);
    if (rc != MOSQ_ERR_SUCCESS) {
        printf("❌ 发起连接失败: %s\n", mosquitto_strerror(rc));
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        return 1;
    }
    
    // 启动网络循环
    rc = mosquitto_loop_start(mosq);
    if (rc != MOSQ_ERR_SUCCESS) {
        printf("❌ 启动网络循环失败: %s\n", mosquitto_strerror(rc));
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        return 1;
    }
    
    // 等待连接建立
    sleep(3);
    
    // 主循环 - 定期发送测试消息
    int message_count = 0;
    while (running) {
        sleep(5);
        
        if (running) {
            char message[256];
            snprintf(message, sizeof(message), 
                    "测试消息 #%d，时间: %ld", 
                    ++message_count, time(NULL));
            
            printf("📤 发送测试消息: %s\n", message);
            rc = mosquitto_publish(mosq, NULL, TEST_TOPIC, strlen(message), message, 0, false);
            if (rc != MOSQ_ERR_SUCCESS) {
                printf("❌ 发送消息失败: %s\n", mosquitto_strerror(rc));
            }
        }
    }
    
    printf("\n🛑 正在断开连接...\n");
    
    // 清理资源
    mosquitto_loop_stop(mosq, true);
    mosquitto_disconnect(mosq);
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();
    
    printf("✅ 程序正常退出\n");
    return 0;
}

/*
编译和测试说明:

1. 编译:
   gcc -o mqtt_test_simple mqtt_test_simple.c -lmosquitto

2. 运行:
   ./mqtt_test_simple

3. 在另一个终端测试接收消息:
   mosquitto_sub -h test.mosquitto.org -t "test/simple"

4. 在另一个终端测试发送消息:
   mosquitto_pub -h test.mosquitto.org -t "test/simple" -m "外部测试消息"

5. 如果test.mosquitto.org不可用，可以尝试:
   - broker.emqx.io
   - mqtt.eclipseprojects.io
   - 或者本地mosquitto: localhost
*/